<template>
  <menu-header v-if="refresh" @selectItem="changeItem" :activeTab="activeTab"></menu-header>
  <keep-alive>
    <component :docId="docId" :type="type" :is="currentComponent"></component>
  </keep-alive>
  <div class="version-fix">©2023&nbsp;&nbsp;MEGMEET&nbsp;&nbsp;Copyright&nbsp;&nbsp;V{{ latestVersion }} </div>
</template>
<script>
import MenuHeader from '@/components/home/MenuHeader.vue'
import Index from '@/components/homeIndex/Index.vue'
import DocumentPage from '@/components/homeDoc/DocumentPage.vue'
import ShareSpace from '@/components/homeShareSpace/ShareSpace.vue'
import SolutionTab from '@/components/solution/SolutionTab'
import {onMounted, provide, ref} from 'vue'
import eventBus from '@/utils/event_bus'
import FrontApi from '@/api/front'

// 路径和子组件的映射表
const componentMap = {
  '/default': 'Index',
  '/index': 'Index',
  '/solutionTab':'SolutionTab',
  '/document': 'DocumentPage',
  '/shareSpace': 'ShareSpace'
}

export default {
  name: 'home',
  props:{
    docId:Number,
    type:String
  },
  components: {
    MenuHeader,
    Index,
    DocumentPage,
    ShareSpace,
    SolutionTab
  },
  setup() {
    const id=ref()
    const docType = ref()
    let currentComponent = ref('Index')
    let activeTab = ref('/index')
    let refresh = ref(true)
    const show = ref(false)
    const latestVersion = ref('')

    provide('show',show)
    provide('curComponent',currentComponent)
    provide("latestVersion", latestVersion)

    onMounted(() => {
      FrontApi.getLatestVersion().then(res => {
        if (res.code === 200) {
          latestVersion.value = res.data.version
        }
      })
    })

    return {
      currentComponent,
      activeTab,
      refresh,
      show,
      id,
      latestVersion,
      docType
    }
  },
  methods: {
    changeItem(index) {
      if (Object.hasOwnProperty.call(componentMap, index)) {
        this.activeTab = index
        this.currentComponent = componentMap[index]
        this.$router.push(this.activeTab)
      } else {
        this.refresh = false
        setImmediate(() => {
          this.refresh = true
        })
      }
    }
    ,
    enterPreview(docId,type,index) {
        const to = this.$router.resolve({name: index,params:{docId:docId,type:type}})
        window.open(to.href,"_blank")
    }
  },
  mounted() {
    let pathName = this.$route.path
    this.activeTab = pathName === '/' ? '/index' : pathName
    eventBus.on("jumpToPreview", (data) => {
      this.enterPreview(data.docId,data.type, 'document')
    })
    if(this.activeTab.startsWith("/document/")){
      this.currentComponent = 'DocumentPage'
    }else{

      this.currentComponent = componentMap[this.activeTab ]
    }
  },
  beforeUnmount() {
    eventBus.off("jumpToPreview")
  }
}
</script>
<style scoped>

.version-fix{
  position: fixed;
  z-index: 999;
  right: 0.3%;
  bottom: 0.3%;
  font-size: 1.5rem;
}
</style>